<template>
  <div v-if="accountOptions.length > 1">
    店铺：
    <el-checkbox v-model="checkAll" @change="changeCheckAll">全选</el-checkbox>

    <el-checkbox
      v-for="account in accountOptions"
      :key="account.accountId"
      :value="checkAccountIds.indexOf(account.accountId) !== -1"
      @change="checkAccount(account.accountId)"
    >{{account.showName}}</el-checkbox>
  </div>
</template>

<script>
import {getAllAccountList} from "@/api/account";

export default {
  name: "AccountCheckbox",
  watch:{
    checkAccountIds(){
      this.$emit('input',this.checkAccountIds)
      this.$emit('change',this.checkAccountIds)
    }
  },
  data(){
    return {
      accountOptions: [],
      checkAccountIds: [],
      checkAll: true,
    }
  },
  created() {
    this.getData()
  },
  methods:{
    async getData(){
      await getAllAccountList()
        .then(res=>{
          this.accountOptions = res.data
          this.accountOptions.forEach(item =>{
            this.checkAccountIds.push(item.accountId)
          })
        })
    },
    changeCheckAll(){
      if(this.checkAll){
        this.checkAccountIds = [];
        this.accountOptions.forEach(item=>{
          this.checkAccountIds.push(item.accountId)
        })
      }else{
        this.checkAccountIds = [];
      }
    },
    checkAccount(accountId){
      if(this.checkAll){
        this.checkAccountIds = [accountId];
        this.checkAll = false
      }else{
        // 查询是否在列表内 不在则添加 在则移除
        const index = this.checkAccountIds.indexOf(accountId)
        if(index === -1){
          this.checkAccountIds.push(accountId)
        }else{
          this.checkAccountIds.splice(index,1)
        }
      }
      if(this.checkAccountIds.length === this.accountOptions.length){
        this.checkAll = true
      }
    }
  },
}
</script>

<style scoped>

</style>
